package com.lxy.shiro.controller;

import com.lxy.shiro.model.ResponseData;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author: lxy
 * @Date: 2019/6/27 17:22
 * @Desc: describe this class
 */
@Controller
public class LoginController {

    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public ResponseData login(String username, String password) {
        Subject user = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        ResponseData<String> resp = new ResponseData();
        resp.setStatus(Boolean.FALSE);
        try {
            //shiro帮我们匹配密码什么的，我们只需要把东西传给它，它会根据我们在UserRealm里认证方法设置的来验证
            user.login(token);
            resp.setStatus(Boolean.TRUE);
            resp.setData("success");
            return resp;
        } catch (UnknownAccountException e) {
            //账号不存在和下面密码错误一般都合并为一个账号或密码错误，这样可以增加暴力破解难度
            resp.setData("账号不存在！");
        } catch (DisabledAccountException e) {
            resp.setData("账号未启用！");
        } catch (IncorrectCredentialsException e) {
            resp.setData("密码错误！");
        } catch (Throwable e) {
            resp.setData("未知错误！");
        }
        return resp;
    }


    /**
     * 退出
     *
     * @return
     */
    @GetMapping("/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "login";
    }
}
